#include "cardlistmodel.h"

#include "cardgraphicsitem.h"

#include <QIcon>

#include <algorithm>


#include "carddisplaydock.h"

CardListModel::CardListModel(QObject *parent)
    : QAbstractListModel(parent)
{
}

int CardListModel::rowCount(const QModelIndex &) const
{
    return cards.size();
}

QVariant CardListModel::data(const QModelIndex &index, int role) const
{
    CardGraphicsItem *card = cards[index.row()];
    if (role == Qt::DecorationRole) {
        return QIcon(card->pixmap());
    }
    else {
        return QVariant();
    }
}

void CardListModel::addCard(CardGraphicsItem *card, bool top)
{
    if (top) {
        cards.push_front(card);
    }
    else {
        cards.push_back(card);
    }
    //rowsInserted(QModelIndex(), cards.size()-1, cards.size()-1);
    layoutChanged();
}

CardGraphicsItem *CardListModel::removeTop()
{
    if (cards.isEmpty()) {
        return NULL;
    }

    CardGraphicsItem *result = cards.front();
    cards.pop_front();
    layoutChanged();
    return result;
}

void CardListModel::moveToBattleField( const QModelIndex & index )
{
    CardGraphicsItem *card = cards[index.row()];

    cards.removeOne(card);
    layoutChanged();
    card->sendToBattleField();
}

void CardListModel::shuffle()
{
    std::random_shuffle(cards.begin(), cards.end());
    layoutChanged();
}

void CardListModel::displayCard( const QModelIndex & index )
{
    CardDisplayDock::instance().displayCard(cards[index.row()]->multiverseId());
}
